package main.java.FSMDE.persistence;

import java.util.ArrayList;
import java.util.UUID;

import main.java.ERMDE.infrastructure.StringExtensions;
import main.java.ERMDE.models.Diagram;
import main.java.FSMDE.models.ComponentCollection;
import main.java.FSMDE.models.Interface;
import main.java.FSMDE.models.InterfaceGraphType;
import main.java.FSMDE.models.InterfaceType;
import main.java.FSMDE.persistence.ComponentCollectionXmlManager;
import main.java.common.IXmlManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class InterfaceXmlManager implements IXmlManager<Interface> {

	private ArrayList<Diagram> ermDiagrams;

	public Element getElementFromItem(Interface inface, Document document) {
		Element interfaceElement = document.createElement("interface");

		interfaceElement.setAttribute("name", inface.getName().toString());
		interfaceElement.setAttribute("id", inface.getId().toString());
		interfaceElement.setAttribute("type", inface.getType().name());
		interfaceElement
				.setAttribute("graphType", inface.getGraphType().name());
		interfaceElement.setAttribute("subdiagramName",
				inface.getRelatedSubdiagramName());
		interfaceElement.appendChild(new ComponentCollectionXmlManager(
				ermDiagrams).getElementFromItem(inface.getComponents(),
				document));

		return interfaceElement;
	}

	public Interface getItemFromXmlElement(Element interfaceElement)
			throws Exception {
		if (ermDiagrams == null) {
			ermDiagrams = new ArrayList<Diagram>();
		}
		String name = interfaceElement.getAttribute("name");
		UUID id = UUID.fromString(interfaceElement.getAttribute("id"));
		InterfaceType type = InterfaceType
				.valueOf(StringExtensions.isNullOrEmpty(interfaceElement
						.getAttribute("type")) ? "Default" : interfaceElement
						.getAttribute("type"));
		InterfaceGraphType graphType = InterfaceGraphType
				.valueOf(StringExtensions.isNullOrEmpty(interfaceElement
						.getAttribute("graphType")) ? "Default"
						: interfaceElement.getAttribute("graphType"));
		Element componentsElem = (Element) interfaceElement
				.getElementsByTagName("components").item(0);

		String subdiagramName = interfaceElement.getAttribute("subdiagramName");
		ComponentCollection components = new ComponentCollectionXmlManager(
				ermDiagrams).getItemFromXmlElement(componentsElem);

		Interface inface = new Interface(name, type, graphType);
		if (!subdiagramName.equals("")) {
			inface.setSubDiagram(subdiagramName);
		}
		inface.setComponents(components);
		inface.setId(id);
		return inface;
	}

	public void setErmDiagrams(ArrayList<Diagram> ermDiagrams) {
		this.ermDiagrams = ermDiagrams;
	}
}
